import EchartsComponent, { MyChartOption } from '@/components/EchartsComponent';
import { ProColumns, ProForm, ProFormSelect } from '@/components/Pro';
import { getEmptyOptions } from '@/dictionary';
import { DeviceTreeDataNode } from '@/pages/SiteMonitor/RealtimeMonitoring/types';
import {
  historyCurveControllerDataColumnList,
  historyCurveControllerMetadata,
  historyCurveControllerMetadataList,
} from '@/services/ess/historicalCurve';
import { useIntl } from '@@/exports';
import ProTable from '@ant-design/pro-table';
import { Button, message, Radio, Spin } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

type IProps = {
  currentTreeNode: DeviceTreeDataNode & { path: string[] };
};
export const DailyCurve: React.FC<IProps> = (props) => {
  const intl = useIntl();

  const { currentTreeNode } = props;
  const formRef = useRef(null);
  const [loadingCharts, setLoadingCharts] = useState(false);
  const [type, setType] = useState('list');
  const [tagOptions, setTagOptions] = useState();
  const [chartOptions, setChartOptions] = useState(getEmptyOptions());
  const [currentTags, setCurrentTags] = useState([]);
  const getTagOptions = (currentNode: DeviceTreeDataNode & { path: string[] }) => {
    const params = {
      areaId: currentNode?.areaId,
      deviceType: currentNode?.deviceType,
      deviceCode: currentNode?.deviceCode,
      nodeType: currentNode?.nodeType,
      stat: false,
    };
    historyCurveControllerDataColumnList(params).then((res) => {
      if (res.success) {
        setTagOptions(res.data);
      }
    });
  };
  const chartRef = useRef(null);
  const tableRef = useRef(null);
  const getFormatterOption = (data: API.DataCurveDTO): MyChartOption => {
    const xaxis = data?.xaxis;
    const hasSOC = data.yaxis.some((item) => item.unit === '%');
    const seriesData = data?.yaxis.map((item) => {
      return {
        yAxisIndex: item.unit === '%' ? 1 : 0,
        data: item.pointsValues,
        type: 'line',
        name: `${item.title}${item.unit ? `(${item.unit})` : ''}`,
        showSymbol: false,
        smooth: true,
      };
    });
    return {
      grid: {
        top: '25%',
      },
      dataZoom: {
        type: 'inside',
      },
      xAxis: {
        type: 'category',
        data: xaxis,
        axisLine: {
          show: true,
        },
        axisLabel: {
          formatter: function (params) {
            console.log('label', params);
            return params.slice(-8);
          },
        },
      },
      yAxis: [
        {
          type: 'value',
          axisLine: {
            show: true,
          },
        },
        {
          show: hasSOC,
          type: 'value',
          name: '%',
          axisLine: {
            show: true,
          },
        },
      ],
      legend: {},
      tooltip: {
        trigger: 'axis',
      },
      series: seriesData,
    };
  };
  const getNullTitle = (val: string | null) => {
    if (val === null) {
      return '';
    } else {
      return val + '_';
    }
  };
  const getDataIndex = (item: API.DataColumnDTO): string | undefined => {
    switch (item.nodeType) {
      case 'ROOT':
        return item.dataAttr;
      case 'AREA':
        return `${item.areaId ? item.areaId + '_' : ''}${item.dataAttr}`;
      case 'DEVICE_GROUP':
        return `${item.areaId ? item.areaId + '_' : ''}${
          item.deviceType ? item.deviceType + '_' : ''
        }${item.dataAttr}`;
      case 'DEVICE':
        return `${item.deviceCode ? item.deviceCode + '_' : ''}${item.dataAttr}`;
      default:
        return '';
    }
  };
  const getElseColumns = (tableData: API.DataColumnDTO[]): ProColumns[] => {
    return tableData?.map((item: API.DataColumnDTO) => {
      return {
        title: `${getNullTitle(item.areaName)}${getNullTitle(item.deviceName)}${
          item.dataName || ''
        }${item.unit ? `(${item.unit})` : ''}`,
        dataIndex: getDataIndex(item),
        width: 150,
      };
    });
  };
  const baseColumns: ProColumns[] = [
    {
      title: intl.formatMessage({ id: 'hisCurve.no' }),
      valueType: 'index',
      width: 80,
    },
    {
      title: intl.formatMessage({ id: 'hisCurve.timeSelect' }),
      dataIndex: 'date',
      width: 150,
    },
  ];
  const [elseColumns, setElseColumns] = useState([]);
  const getColumns = baseColumns.concat(elseColumns);

  /**
   * 搜索方法
   *
   */
  const handleSearch = (currentTags) => {
    if (type === 'chart') {
      if (!currentTags || !currentTags.length) {
        message.warning(intl.formatMessage({ id: 'global.leastOne' }));
        chartRef?.current?.instance().clear();
        setChartOptions(getEmptyOptions());
        return false;
      }
      setLoadingCharts(true);
      const params = {
        today: true,
      };
      params.columnList = currentTags.map((item) => {
        return {
          deviceCode: currentTreeNode?.deviceCode,
          deviceType: currentTreeNode?.deviceType,
          deviceName: currentTreeNode?.deviceName,
          nodeType: currentTreeNode?.nodeType,
          areaId: currentTreeNode?.areaId,
          stationCode: currentTreeNode?.stationCode,
          dataAttr: item.dataAttr,
          dataName: item.dataName,
        };
      });
      historyCurveControllerMetadata(params)
        .then((res) => {
          chartRef?.current?.instance().clear();
          setChartOptions(getFormatterOption(res.data));
          setLoadingCharts(false);
        })
        .catch(() => {
          setLoadingCharts(false);
        });
    } else {
      tableRef?.current?.reload();
    }
  };
  useEffect(() => {
    getTagOptions(currentTreeNode);
    setCurrentTags([]);
    formRef?.current?.resetFields();
    handleSearch([]);
    setElseColumns([]);
  }, [currentTreeNode]);
  useEffect(() => {
    handleSearch(currentTags);
  }, [type]);
  return (
    <div style={{ padding: 20 }}>
      <ProForm
        layout={'inline'}
        submitter={false}
        formRef={formRef}
        params={{
          type: type,
        }}
      >
        <ProFormSelect
          style={{ width: 200 }}
          name={'selectedTag'}
          label={intl.formatMessage({ id: 'hisCurve.dataItem' })}
          options={tagOptions}
          fieldProps={{
            onChange: (e, params) => {
              setCurrentTags(params);
            },
            mode: 'multiple',
            maxTagCount: 'responsive',
            fieldNames: {
              label: 'dataName',
              value: 'dataAttr',
            },
          }}
        ></ProFormSelect>
        <ProForm.Item>
          <Button
            type={'primary'}
            onClick={() => {
              handleSearch(currentTags);
            }}
          >
            {intl.formatMessage({ id: 'global.search' })}
          </Button>
        </ProForm.Item>
      </ProForm>
      <div style={{ marginTop: 10 }}>
        <Radio.Group
          optionType="button"
          buttonStyle="solid"
          value={type}
          onChange={(e) => {
            const { value } = e.target;
            setType(value);
          }}
        >
          <Radio.Button value={'list'}>
            {intl.formatMessage({ id: 'statistics.common.list' })}
          </Radio.Button>
          <Radio.Button value={'chart'}>
            {intl.formatMessage({ id: 'statistics.common.chart' })}
          </Radio.Button>
        </Radio.Group>
        <div style={{ marginTop: 10 }}>
          {type === 'chart' ? (
            <div>
              <Spin spinning={loadingCharts}>
                <EchartsComponent
                  option={chartOptions}
                  height={500}
                  ref={chartRef}
                ></EchartsComponent>
              </Spin>
            </div>
          ) : (
            <div>
              <ProTable
                scroll={{ y: 450 }}
                toolBarRender={false}
                actionRef={tableRef}
                columns={getColumns}
                search={false}
                params={{
                  type: type,
                }}
                request={async () => {
                  if (!currentTags || !currentTags.length) {
                    message.warning(intl.formatMessage({ id: 'global.leastOne' }));

                    return false;
                  }
                  const params = {
                    today: true,
                  };
                  params.columnList = currentTags.map((item) => {
                    return {
                      deviceCode: currentTreeNode?.deviceCode,
                      deviceType: currentTreeNode?.deviceType,
                      deviceName: currentTreeNode?.deviceName,
                      stationCode: currentTreeNode?.stationCode,
                      nodeType: currentTreeNode?.nodeType,
                      areaId: currentTreeNode?.areaId,
                      dataAttr: item.dataAttr,
                      dataName: item.dataName,
                    };
                  });
                  const res = await historyCurveControllerMetadataList(params);
                  if (res.success) {
                    setElseColumns(getElseColumns(res?.data?.dataColumnList));
                  }
                  return {
                    success: res.success,
                    data: res?.data?.dataList,
                  };
                }}
              ></ProTable>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};
